﻿var treeActionUrl = "FileTreeActions.ashx";

var $tree = { "currentRootId": "" };
var logs = new Array();
logs.Add = function (text) {
	this[this.length] = text;
};

var NodeTagTemplate
	= '<div class="NodeTagDiv">'
		+ '{ShowNoneChildIcon?<span class="toggleIcoPlace"></span>|}'
		+ '{ShowPopulateExpandIcon?<span class="toggleIcoToExpand" title="展开" onclick="$tree.LoadChildren(this);"></span>|}'
		+ '{ShowCollapseIcon?<span class="toggleIcoExpanded" title="折叠" onclick="$tree.ToggleChildrenShow(this);"></span>|}'
		+ '{ShowExpandIcon?<span class="toggleIcoCollapsed" title="展开" onclick="$tree.ToggleChildrenShow(this);"></span>|}'
		+ '<a class="NodeTag" href="[NavigateHref]" draggable="true" ondragstart="return $tree.NodeDragstart(this,event);" ondragover="return $tree.NodeDragover(this,event);" ondragleave="return $tree.NodeDragleave(this,event);" ondrop="return $tree.NodeDrop(this,event);" onclick="$tree.SetOperationFocus(this);return false;" oncontextmenu="return $tree.NodeContextMenu(this,event);">'
		+ '{ShowTypeIcon?<img src="filetypeIcon/[TypeIcon].gif" onerror="this.src=\'filetypeIcon/Unknown.gif\'" alt="" onclick="" class="typeIcon" />|}'
		+ '{ShowCheckBox?<input type="checkbox" <:checked="[Checked]"> onclick="checkBox(this);" class="checkbox" />|}'
		+ '<span onclick="return $tree.OnNodeClick(this);" target="[NavigateTarget]" title="[ToolTip]">[Value]</span>'
		+ '</a>'
	+ '</div>';
var NodeChildrenTemplate
	= '<div class="ChildrenDiv" data-value="[Value]"></div>';
var TreeNodeHtmlTemplate
	= '<div>'
		+ NodeTagTemplate
		+ NodeChildrenTemplate
	+ '</div>';

(function (Tree) {
	var TreeConfig = { "ShowDepth": 10 };

	Tree.init = function (Setting) {
		for (var key in TreeConfig) {
			if (typeof Setting[key] == "undefined") Setting[key] = TreeConfig[key];
		}
		var RootId = Setting["RootId"];
		Tree[RootId] = {};
		Tree[RootId].Setting = Setting;
		Tree[RootId].RootNodes = [];
		Tree[RootId].PathTree = {};
		Tree[RootId].FocusTagNode = null;
		//Tree[RootId].FocusValuePath = "/";
		Tree[RootId].RootNodeDiv = document.getElementById(RootId);
		if (typeof Setting.contextmenu != "undefined") {
			var cNodes = document.body.childNodes;
			for (var i = 0; i < cNodes.length; i++) {
				if (cNodes[i].nodeType != 1) continue;
				if (document.all) {
					cNodes[i].attachEvent('onmousedown', clearContextMenu);
				}
				else {
					cNodes[i].addEventListener('mousedown', clearContextMenu, false);
				}
			}
		}
	}

	Tree.OnNodeClick = function (aNode) {
	}

	Tree.NodeDragstart = function (node, eventTag) {
		var ev = window.event || eventTag;
		var anchorLabel = ev.target || ev.srcElement;
		if (anchorLabel.nodeName != "A") anchorLabel = anchorLabel.parentNode;

		var idValuePath = getIdValuePath(anchorLabel.parentNode.nextSibling);
		if (ev.dataTransfer.setData) {
			ev.dataTransfer.setData("text", idValuePath);
		}

		var toggleIcon = anchorLabel.previousSibling;
		if (toggleIcon.className == "toggleIcoExpanded")
			Tree.ToggleChildrenShow(toggleIcon);

		if (ev.dataTransfer.effectAllowed) {
			ev.dataTransfer.effectAllowed = "move";
		}
		if (ev.dataTransfer.setDragImage) {
			var clonedNode = anchorLabel.cloneNode(true);
			ev.dataTransfer.setDragImage(clonedNode, 0, 0);
		}



		return true;
	}
	Tree.NodeDragleave = function (node, eventTag) {
		if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
			Tree.dragIndicator.style.display = "none";
		return true;
	}
	Tree.NodeDragover = function (node, eventTag) {
		var ev = window.event || eventTag;
		var anchorLabel = ev.target || ev.srcElement;
		if (anchorLabel.nodeName != "A") anchorLabel = anchorLabel.parentNode;

		var idValuePath = getIdValuePath(anchorLabel.parentNode.nextSibling);
		//$("#logWatcher").val(idValuePath+"|"+ev.dataTransfer.getData("text")+"\n"+$(logWatcher).val());
		var transferPath = ev.dataTransfer.getData("text") //chrome: transferPath → undefined
		if (transferPath == idValuePath) {
			if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
				Tree.dragIndicator.style.display = "none";
			return true;
		}
		var toggleIcon = anchorLabel.previousSibling;
		var offsetY = $(anchorLabel).offset().top;
		if (ev.clientY - offsetY < 5) {
			if (anchorLabel.parentNode.parentNode.previousSibling)
				if (transferPath == getIdValuePath(anchorLabel.parentNode.parentNode.previousSibling.lastChild)) {
					if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
						Tree.dragIndicator.style.display = "none";
					return true;
				}
		} else if (ev.clientY - offsetY > 14) {
			if (anchorLabel.parentNode.parentNode.nextSibling)
				if (transferPath == getIdValuePath(anchorLabel.parentNode.parentNode.nextSibling.lastChild)) {
					if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
						Tree.dragIndicator.style.display = "none";
					return true;
				}
		} else {
			if (toggleIcon.className == "toggleIcoPlace") {
				if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
					Tree.dragIndicator.style.display = "none";
				return true;
			}
		}

		if (typeof Tree.dragIndicator == "undefined") {
			Tree.dragIndicator = createDragIndicator();
		} else if (Tree.dragIndicator.style.display == "none")
			Tree.dragIndicator.style.display = "";
		var dragIndicator = Tree.dragIndicator;
		var offsetX = $(anchorLabel).offset().left;
		var x = ev.clientY - offsetY < 5 ? offsetX : (ev.clientY - offsetY < 15 ? offsetX + 3 : offsetX);
		var y = ev.clientY - offsetY < 5 ? offsetY : (ev.clientY - offsetY < 15 ? offsetY + 10 : offsetY + 20);
		if (dragIndicator.offsetLeft + 5 != x) dragIndicator.style.left = (x - 5) + "px";
		if (dragIndicator.offsetTop + 5 != y) dragIndicator.style.top = (y - 5) + "px";
		if (dragIndicator.style.display == "none") dragIndicator.style.display == "";

		if (ev.clientY - offsetY > 4 && ev.clientY - offsetY < 15) {
			//鼠标停留500毫秒，延时展开子节点
			if (toggleIcon.className == "toggleIcoCollapsed")
				Tree.ToggleChildrenShow(toggleIcon);

			if (toggleIcon.className == "toggleIcoToExpand")
				Tree.LoadChildren(toggleIcon);
		}
		//ev.preventDefault();
		return false;

	}


	Tree.NodeDrop = function (node, eventTag) {
		var ev = window.event || eventTag;

		if (typeof Tree.dragIndicator != "undefined" && Tree.dragIndicator.style.display != "none")
			Tree.dragIndicator.style.display = "none";
		return true;
	}

	function createDragIndicator() {
		var indicator = document.createElement("div");
		indicator.className = "DragIndicator";
		document.body.insertBefore(indicator, document.body.firstChild);
		return indicator;
	}

	var submiting = new Object();

	//function getPathTreeJson(pathTree)
	//{
	//	var strings = new Array();
	//	for (var key in pathTree)
	//	{
	//		strings[strings.length] = '"' + key + '":' + getPathTreeJson(pathTree[key]);
	//	}
	//	return "{" + strings.join(",") + "}";
	//}

	function syncPathTree(rootId, valuePath, toAdd) {
		var paths = valuePath.split("/");

		var currentNode = Tree[rootId].PathTree;
		for (var i = 1; i < paths.length - 2; i++) {
			if (typeof currentNode[paths[i]] == "undefined") {
				currentNode[paths[i]] = {};
			}
			currentNode = currentNode[paths[i]];
		}
		var lastPath = paths[paths.length - 2];
		if (toAdd) {
			if (typeof currentNode[lastPath] == "undefined")
				currentNode[lastPath] = {};
		} else {
			if (typeof currentNode[lastPath] != "undefined")

				delete currentNode[lastPath];
		}

	}

	function getPathNodeData(rootId, valuePath) {
		//if (valuePath == "/") return Tree[RootId].RootNodes;
		var paths = valuePath.split("/");
		var currentNodes = Tree[rootId].RootNodes;
		for (var i = 1; i < paths.length - 2; i++) {
			var found = false;
			for (var j = 0; j < currentNodes.length; j++) {
				if (currentNodes[j].Value == paths[i]) {
					currentNodes = currentNodes[j].ChildNodes;
					found = true;
					break;
				}
			}
			if (!found) { alert("path error"); }
		}
		var lastPath = paths[paths.length - 2];
		var found2 = false;
		for (var k = 0; k < currentNodes.length; k++) {
			if (currentNodes[k].Value == lastPath) {
				return currentNodes[k];
			}
		}
		if (!found2) { alert("path error"); }
	}
	function getPathNodeDiv(valuePath) {
		var paths = valuePath.split("/");
		var indexes = [];
		var currentNodes = TreesDeposit[RootId].RootNodes;
		for (var i = 1; i < paths.length - 1; i++) {
			var found = false;

			for (var j = 0; j < currentNodes.length; j++) {
				if (currentNodes[j].Value == paths[i]) {
					currentNodes = currentNodes[j].ChildNodes;
					indexes.push(j);
					found = true;
					break;
				}
			}
			if (!found) { alert("path error"); }
		}
		var nodeDiv = Tree[rootId].RootNodeDiv.childNodes[indexes[0]];
		for (var k = 1; k < indexes.length; k++) {
			nodeDiv = nodeDiv.childNodes[1].childNodes[indexes[k]];
		}
		return nodeDiv;
	}

	Tree.SetOperationFocus = function (tagNode) {
		var idValuePath = getIdValuePath(tagNode.parentNode.nextSibling);
		var rootId = idValuePath.split(":")[0];
		//var valuePath = idValuePath.split(":")[1];
		Tree.currentRootId = rootId;
		if (Tree[rootId].FocusTagNode != null) Tree[rootId].FocusTagNode.className = "NodeTag";
		tagNode.className = "FocusNodeTag";
		Tree[rootId].FocusTagNode = tagNode;
	}

	function syncNodeChildren(rootId, valuePath, children) {
		if (valuePath == "/") {
			Tree[rootId].RootNodes = children;

			return;
		}
		var paths = valuePath.split("/");

		var pathNode = getPathNodeData(rootId, valuePath);
		pathNode.ChildNodes = children;
	}

	var refreshSubmiting = false;
	Tree.Refresh = function (RootId) {
		if (refreshSubmiting) return;
		var startTime = new Date();
		logs.Add(startTime.toLocaleTimeString() + "：" + "刷新所有展开节点.");
		var pathTreeDate = jsonSerialize(Tree[RootId].PathTree);

		jQuery.ajax({
			type: "POST",
			url: treeActionUrl+"?action=Refresh",
			data: "PathTree=" + pathTreeDate,
			dataType: "json",
			beforeSend: function () {
				refreshSubmiting = true;
			},
			success: function (Json) {
				var endTime = new Date();
				if (Json.Result) {
					Tree[rootId].RootNodeDiv.innerHTML = getTreeHtml(Json.ContentObject);
					logs.Add(endTime.toLocaleTimeString() + "：" + "完成所有展开节点刷新，历时" + (endTime.getTime() - startTime.getTime()) + "毫秒;");
				}
				else {
					alert("刷新所有展开节点失败：  " + Json.ResultMessage);
					logs.Add(endTime.toLocaleTimeString() + "：" + "刷新所有展开节点失败，历时" + (endTime.getTime() - startTime.getTime()) + "毫秒;");

				}
			},
			complete: function () {
				refreshSubmiting = false;
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) { if (typeof XMLHttpRequest == "object") alert(XMLHttpRequest.responseText == "" ? textStatus : XMLHttpRequest.responseText); else alert(XMLHttpRequest); }
		});

	}

	Tree.LoadChildren = function (ToggleIcon, ChildrenDiv) {
		if (typeof ChildrenDiv == "undefined" || ChildrenDiv == null) {
			ChildrenDiv = ToggleIcon.parentNode.nextSibling;
		}

		var idValuePath = getIdValuePath(ChildrenDiv);
		var rootId = idValuePath.split(":")[0];
		var valuePath = idValuePath.split(":")[1];

		if (submiting[idValuePath] == true) return;
		if (ToggleIcon != null) {
			syncPathTree(rootId, valuePath, true);
		}

		var startTime = new Date();
		logs.Add(startTime.toLocaleTimeString() + "：" + "正在载入“" + idValuePath + "”;");

		jQuery.ajax({
			type: "POST",
			url: treeActionUrl+"?action=LoadChildren&rootid="+rootId,
			data: "ValuePath=" + valuePath,
			dataType: "json",
			beforeSend: function () {
				submiting[idValuePath] = true;
				if (ToggleIcon != null) {
					ToggleIcon.onclick = null;
					ToggleIcon.className = "toggleIcoLoading";
					ToggleIcon.title = "正在载入……";
				}
			},
			success: function (Json) {
				var endTime = new Date();
				if (Json.Result) {
					var children = Json.ContentObject;
					syncNodeChildren(rootId, valuePath, children);
					ChildrenDiv.innerHTML = getTreeNodesHtml(Json.ContentObject);
					logs.Add(endTime.toLocaleTimeString() + "：" + "完成载入“" + idValuePath + "”，历时" + (endTime.getTime() - startTime.getTime()) + "毫秒;");
				}
				else {
					alert("LoadChildrens失败：  " + Json.ResultMessage);
					logs.Add(endTime.toLocaleTimeString() + "：" + "LoadChildrens失败“" + idValuePath + "”，历时" + (endTime.getTime() - startTime.getTime()) + "毫秒;");
				}
				if (ToggleIcon != null) {
					ToggleIcon.onclick = function () { $tree.ToggleChildrenShow(this) };
					ToggleIcon.className = "toggleIcoExpanded";
					ToggleIcon.title = "折叠";
					ToggleIcon.style.cursor = "pointer";
				}
			},
			complete: function () {
				submiting[idValuePath] = false;
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) { if (typeof XMLHttpRequest == "object") alert(XMLHttpRequest.responseText == "" ? textStatus : XMLHttpRequest.responseText); else alert(XMLHttpRequest); }

		});

	}

	Tree.ToggleChildrenShow = function (ToggleIcon) {
		var ChildrenDiv = ToggleIcon.parentNode.nextSibling;
		var idValuePath = getIdValuePath(ChildrenDiv);
		var rootId = idValuePath.split(":")[0];
		var valuePath = idValuePath.split(":")[1];
		var curVisiable = ChildrenDiv.style.display != "none";
		ChildrenDiv.style.display = curVisiable ? "none" : "";
		ToggleIcon.className = curVisiable ? "toggleIcoCollapseed" : "toggleIcoExpanded";
		ToggleIcon.title = curVisiable ? "展开" : "折叠";
		syncPathTree(rootId, valuePath, !curVisiable);
	}

	Tree.NodeContextMenu = function (NodeTag, eventTag) {
		Tree.SetOperationFocus(NodeTag);
		var ev = window.event || eventTag;
		var ChildrenDiv = NodeTag.parentNode.nextSibling;
		var idValuePath = getIdValuePath(ChildrenDiv);
		var rootId = idValuePath.split(":")[0];
		var valuePath = idValuePath.split(":")[1];
		if (typeof Tree[rootId].Setting.contextmenu == "undefined") return false;

		Tree.currentRootId = rootId;
		var eventCoordX = ev.clientX;
		var eventCoordY = ev.clientY;
		Tree.lastMenuCoord = { "X": eventCoordX, "Y": eventCoordY };
		var menuSetting = Tree[rootId].Setting.contextmenu;
		if (typeof menuSetting != "object")
			menuSetting = defaultContextmenu;
		var typeClass = NodeTag.previousSibling.className;
		var contextMenu;
		if (typeClass == "toggleIcoPlace") {
			if (typeof Tree.fileContextMenu == "undefined") {
				Tree.fileContextMenu = createContextMenu(menuSetting["file"]);
			}
			contextMenu = Tree.fileContextMenu;
		} else {

			if (typeof Tree.folderContextMenu == "undefined") {
				Tree.folderContextMenu = createContextMenu(menuSetting["folder"]);
			}
			contextMenu = Tree.folderContextMenu;
		}
		contextMenu.style.visibility = "visible";
		var menuWidth = (contextMenu.lastChild.clientWidth + 2);
		var menuHeight = (contextMenu.lastChild.clientHeight + 2);
		//StatusBarDiv.innerHTML="mw:"+mw+"; mh:"+mh+"; x:"+x+"; y:"+y+"; w:"+w+"; h:"+h;
		var menuPosition = getPosition(menuWidth, menuHeight, eventCoordX, eventCoordY);
		//Tree.menuPosition=menuPosition;
		contextMenu.style.left = menuPosition.X + "px";
		contextMenu.style.top = menuPosition.Y + "px";
		contextMenu.style.zIndex = "100";
		contextMenu.firstChild.style.zIndex = "450";
		contextMenu.lastChild.style.zIndex = "460";
		var i = 0;
		for (var key in menuSetting) {
			if (menuSetting[key].submenu) {
				var subMenu = contextMenu.lastChild.childNodes[i].lastChild.lastChild;
				//subMenu.style.visibility="visible";

				subMenu.style.zIndex = "200";
				subMenu.firstChild.style.zIndex = "470";
				subMenu.lastChild.style.zIndex = "480";
			}
			i++;
		}

		contextMenu.focus();
		return false;

		function createContextMenu(menuConfig) {
			var htmlHead = '<ul class="menuWrap">';
			var itemHtmls = [];
			for (var key in menuConfig) {
				if (key == "separator")
					itemHtmls.push('<li style="border-top:#9a9a9a 1px solid;border-bottom:#eee 1px solid;font-size:0;line-height:0;"></li>');
				else {
					var item = menuConfig[key];
					itemHtmls.push('<li><a href="#" onclick="return false;">' + item["label"] + '</a></li>');
				}
			}
			var htmlFoot = '</ul>';
			var menuBody = document.createElement("div");
			menuBody.className = "ContextMenu";
			menuBody.oncontextmenu = function () { return false; };
			//menuBody.style.visibility = "hidden";
			menuBody.innerHTML = htmlHead + itemHtmls.join("") + htmlFoot;
			document.body.insertBefore(menuBody, document.body.firstChild);
			var lis = menuBody.firstChild.childNodes;
			var i = 0;
			for (var key in menuConfig) {
				var li = lis[i];
				if (key != "separator") {
					if (menuConfig[key].action) {
						if (document.all) {
							li.firstChild.attachEvent('onclick', function () { clearContextMenu(); return false; });
						}

						else {
							li.firstChild.addEventListener('click', function () { clearContextMenu(); return false; }, false);
						}
						li.firstChild.onclick = menuConfig[key].action;
					} else if (menuConfig[key].submenu) {
						li.firstChild.className = "hasSubMenu";
						var subMenuDiv = createContextMenu(menuConfig[key].submenu);
						li.firstChild.appendChild(subMenuDiv);
					}
				} else {
					//li.firstChild.onclick = function(){return false;};
				}
				i++;
			}
			menuBody.onkeydown = function () { onEscKeyDown(event); }
			var menuBg = document.createElement("div");
			menuBg.className = "ContextMenuBg";
			menuBg.innerHTML = "&nbsp;";
			menuBg.style.width = (menuBody.firstChild.clientWidth + 2) + "px";
			menuBg.style.height = (menuBody.firstChild.clientHeight + 2) + "px";
			menuBody.insertBefore(menuBg, menuBody.firstChild);
			return menuBody;
		}
	}
	function onEscKeyDown(eventTag) {
		var ev = window.event || eventTag;
		var currentKey = ev.charCode || ev.keyCode;
		if (currentKey == 27) {
			clearContextMenu();


		}

	}

	function clearContextMenu() {

		if (typeof Tree.fileContextMenu != "undefined") {

			Tree.fileContextMenu.style.visibility = "hidden";

		}

		if (typeof Tree.folderContextMenu != "undefined") {

			Tree.folderContextMenu.style.visibility = "hidden";

		}

	}

})($tree);

function getTreeNodeHtmlRecursive(TreeNode) {
	var html = TemplateReplace(TreeNodeHtmlTemplate, TreeNode,
	{
		"ShowNoneChildIcon": TreeNode["ExpandCollapseStatus"] == 0,
		"ShowPopulateExpandIcon": TreeNode["ExpandCollapseStatus"] == 1,
		"ShowCollapseIcon": TreeNode["ExpandCollapseStatus"] == 2,
		"ShowExpandIcon": TreeNode["ExpandCollapseStatus"] == 3,
		"ShowTypeIcon": TreeNode["ShowTypeIcon"],
		"ShowCheckBox": TreeNode["ShowCheckBox"]
	});
	var htmls = [html.substring(0, html.length - 12)];
	if (TreeNode.ChildNodes != null) {
		for (var i = 0; i < TreeNode.ChildNodes.length; i++) {
			htmls[htmls.length] = getTreeNodeHtmlRecursive(TreeNode.ChildNodes[i]);
		}
	}
	htmls[htmls.length] = "</div></div>";
	return htmls.join("");
}

function getTreeNodesHtml(TreeNodes) {
	var htmls = new Array();
	for (var i = 0; i < TreeNodes.length; i++) {
		htmls[i] = getTreeNodeHtmlRecursive(TreeNodes[i]);
	}
	return htmls.join("");
}


function getPosition(width, height, coordX, coordY) {
	var bodyWidth = document.body.clientWidth != 0 ? document.body.clientWidth : (document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.offsetWidth);
	var bodyHeight = document.body.clientHeight != 0 ? document.body.clientHeight : (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.offsetHeight);
	var pos = {};
	if (coordX < width) {
		pos.X = coordX;
	} else {
		if (bodyWidth - coordX < width) {
			pos.X = coordX - width;
		} else {
			pos.X = coordX;
		}
	}
	if (coordY < height) {
		pos.Y = coordY;
	} else {
		if (bodyHeight - coordY < height) {
			pos.Y = coordY - height;
		} else {
			pos.Y = coordY;
		}
	}
	return pos;
}

function getIdValuePath(ChildrenDiv) {
	if (ChildrenDiv.getAttribute("data-value") == null) return ChildrenDiv.id + ":/";

	var paths = new Array();
	paths[0] = ChildrenDiv.getAttribute("data-value");
	var parentContainer = ChildrenDiv.parentNode.parentNode;
	while (parentContainer.getAttribute("data-value") != null) {
		paths[paths.length] = parentContainer.getAttribute("data-value");
		parentContainer = parentContainer.parentNode.parentNode;
	}
	paths = paths.reverse();
	var idValuePath = parentContainer.id + ":/" + paths.join("/");
	if (ChildrenDiv.previousSibling.firstChild.className != "toggleIcoPlace")
		idValuePath = idValuePath + "/";
	return idValuePath;
}

var defaultContextmenu = {
	"folder": {
		"createFolder": {
			"label": "新建文件夹",
			"action": function () { ShowCreateFolderDialog(); }
		},
		"createFile": {
			"label": "新建文件",
			"action": function () { alert("??"); }
		},
		"separator": {},
		"rename": {
			"label": "重命名",
			"action": function () { ShowRenameInput(); }
		},
		"remove": {
			"label": "Delete",
			"action": function (obj) { alert(typeof this); }
		}
	},
	"file": {
		"rename": {
			"label": "重命名",
			"action": function () { ShowRenameInput(); }
		},
		"Delete": {
			"label": "删除",
			"action": function (obj) { alert(typeof this); }
		},
		"ccp": {
			"label": "编辑",
			"action": false,
			"submenu": {
				"cut": {
					"label": "Cut",
					"action": function (obj) { this.cut(obj); }
				},
				"copy": {
					"label": "Copy",
					"action": function (obj) { this.copy(obj); }
				},
				"paste": {
					"label": "Paste",
					"action": function (obj) { this.paste(obj); }
				}
			}
		}
	}
};


function ShowRenameInput() {
	var focusTag = $tree[$tree.currentRootId].FocusTagNode;
	var namespan = focusTag.firstChild.nextSibling;
	namespan.style.display = "none";
	var textbox = document.createElement("input");
	namespan.parentNode.parentNode.appendChild(textbox);
	textbox.type = "text";
	textbox.value = namespan.firstChild.data;
	textbox.className = "renameInput";
	textbox.focus();
	textbox.select();
	textbox.oncontextmenu = function (event) {
		if (window.event) {
			window.event.cancelBubble = true;
		} else {
			event.stopPropagation();
		}
	};
	textbox.onblur = function () {
		DoRename(this);
	};
	textbox.onkeydown = function (event) {
		event = window.event || event;
		if (event.keyCode == 13) {
			this.blur();
			DoRename(this);
			return false;
		} else if (event.keyCode == 27) {
			clearShownRename(this);
		}
	};
}

function clearShownRename(textbox) {
	textbox.onblur = null;
	textbox.blur();
	var namespan = textbox.previousSibling.lastChild;
	textbox.parentNode.removeChild(textbox);
	namespan.style.display = "";
}

function DoRename(textbox) {
	var namespan = textbox.previousSibling.lastChild;
	if (textbox.value != namespan.firstChild.data) {
		var ChildrenDiv = namespan.parentNode.parentNode.nextSibling;
		var idValuePath = getIdValuePath(ChildrenDiv);
		var rootId = idValuePath.split(":")[0];
		var valuePath = idValuePath.split(":")[1];

		var toggleIcoClass = namespan.parentNode.previousSibling.className;
		var destinationName = textbox.value;
		var destinationParentPath;
		var action;
		if (toggleIcoClass == "toggleIcoPlace") {
			action = "MoveFileNode";
			var destinationParentPath = valuePath.substring(0, valuePath.lastIndexOf("/"));
			destinationName = destinationParentPath + destinationName;
		} else {
			action = "MoveFolderNode";
			var destinationParentPath = valuePath.substring(0, valuePath.lastIndexOf("/", valuePath.length - 2) + 1);
			destinationName = destinationParentPath + destinationName + "/";
		}
		var sourceName = valuePath;
		jQuery.ajax({
			type: "POST",
			url: treeActionUrl+"?action="+action+"&rootid="+rootId,
			data: "sourceName=" + sourceName + "&destinationPath=" + destinationName,
			dataType: "json",
			beforeSend: function () {
			},
			success: function (Json) {
				if (Json.Result) {
					namespan.firstChild.data = textbox.value;
					ChildrenDiv.setAttribute("data-value", textbox.value);
					clearShownRename(textbox);
				} else {
					textbox.onblur = null;
					alert("重命名失败：  " + Json.ResultMessage);
					textbox.onblur = function () { DoRename(this); };
				}
			},
			complete: function () {
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				textbox.onblur = null;
				if (typeof XMLHttpRequest == "object") alert(XMLHttpRequest.responseText == "" ? textStatus : XMLHttpRequest.responseText); else alert(XMLHttpRequest);
				textbox.onblur = function () { DoRename(this); };
			}
		});
	} else {
		clearShownRename(textbox);
	}
}


function ShowCreateFolderDialog() {
	var rootId = $tree.currentRootId;
	var NodeTag = $tree[rootId].FocusTagNode;


	var CreateFolderDialog = document.getElementById("CreateFolderDialog");
	var Width = CreateFolderDialog.clientWidth;
	var Height = CreateFolderDialog.clientHeight;
	var pos = getPosition(Width, Height, $tree.lastMenuCoord.X, $tree.lastMenuCoord.Y);
	CreateFolderDialog.style.left = pos.X + "px";
	CreateFolderDialog.style.top = pos.Y + "px";

	CreateFolderDialog.style.visibility = "visible";
	$("#NewFolderName").focus();
}

var createSubmiting = new Object();
function CreateFolderSubmit(actionType, newname) {
	var rootId = $tree.currentRootId;
	var NodeTag = $tree[rootId].FocusTagNode;
	var idValuePath = getIdValuePath(NodeTag.parentNode.nextSibling);
	var valuePath = idValuePath.split(":")[1];
	var newFolderName = $("#NewFolderName").val();
	var newNode = { "Value": newFolderName, "ExpandCollapseStatus": 1, "ShowTypeIcon": true, "TypeIcon": "_folder" };
	var nodeStr = jsonSerialize(newNode);

	jQuery.ajax({
		type: "POST",
		url: treeActionUrl+"?action="+"CreateFolderNode"+"&rootid="+rootId,
		data: "sourcePath=" + valuePath + "&node=" + encodeURIComponent(nodeStr),
		dataType: "json",
		beforeSend: function () {
			createSubmiting[idValuePath] = true;
		},
		success: function (Json) {
			if (Json.Result) {
				var div = document.createElement("div");
				var nodeHtml = getTreeNodeHtmlRecursive(newNode);
				div.innerHTML = nodeHtml;
				NodeTag.parentNode.nextSibling.appendChild(div.firstChild);
				var CreateFolderDialog = document.getElementById("CreateFolderDialog");
				CreateFolderDialog.style.visibility = "hidden";
			}
			else {
				alert("新建文件夹失败：  " + Json.ResultMessage);
			}
		},
		complete: function () {
			createSubmiting[idValuePath] = false;
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) { if (typeof XMLHttpRequest == "object") alert(XMLHttpRequest.responseText == "" ? textStatus : XMLHttpRequest.responseText); else alert(XMLHttpRequest); }
	});
}

function CreateChildNode(currentPath) {

}

var deleteSubmiting = new Object();
function DeleteNode() {
	var rootId = Tree.currentRootId;
	//var valuePath = Tree[rootId].FocusValuePath;
	var idValuePath = rootId + ":" + valuePath;
	var NodeTag = Tree[rootId].FocusTagNode;

	jQuery.ajax({
		type: "POST",
		url: treeActionUrl+"?action="+"DeleteNode"+"&rootid="+rootId,
		data: "ValuePath=" + valuePath,
		dataType: "json",
		beforeSend: function () {
			deleteSubmiting[idValuePath] = true;
		},
		success: function (Json) {
			if (Json.Result) {
				NodeTag.parentNode.parentNode.parentNode.removeChild(NodeTag.parentNode.parentNode);
				logs.Add("已删除：" + valuePath + "");
			}
			else {
				alert("删除" + valuePath + "失败：  " + Json.ResultMessage);
				var endTime = new Date();
				logs.Add("删除" + valuePath + "失败：  " + Json.ResultMessage);
			}
		},
		complete: function () {
			deleteSubmiting[idValuePath] = false;
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) { if (typeof XMLHttpRequest == "object") alert(XMLHttpRequest.responseText == "" ? textStatus : XMLHttpRequest.responseText); else alert(XMLHttpRequest); }
	});
}

